package com.android.kotlincoroutinemvvmdemo.base
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.android.kotlincoroutinemvvmdemo.Constants
import com.android.kotlincoroutinemvvmdemo.CoroutineMVVMApp
import com.android.kotlincoroutinemvvmdemo.R
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity(), CoroutineScope by MainScope() {

    protected lateinit var mBinding : T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, getLayoutId())
        init(savedInstanceState)

        adapterUIModeNightForActivity(CoroutineMVVMApp.instance!!.isDarkTheme())
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        var dayNightYes = false
        when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
            Configuration.UI_MODE_NIGHT_YES -> {
                //深色模式
                adapterUIModeNightForActivity(true)
                dayNightYes = true

                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            }
            Configuration.UI_MODE_NIGHT_NO -> {
                //浅色模式
                adapterUIModeNightForActivity(false)
                dayNightYes = false

                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
            else -> {}
        }

        //适配底部导航栏颜色
        adapterNavigationBar()

        val intent = Intent()
        intent.putExtra(Constants.DAY_NIGHT_FLAG, dayNightYes)
        intent.action = Constants.DAY_NIGHT_UI_MODE_CHANGE
        sendBroadcast(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.unbind()
    }

    abstract fun getLayoutId() : Int

    abstract fun init(savedInstanceState: Bundle?)

    open fun adapterUIModeNightForActivity(uiModeNight: Boolean) {}

    private fun adapterNavigationBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = resources.getColor(R.color.color_dn_black_white)
        }
    }

    open fun adapterStatusBar(color: Int) {
        ImmersionBar.with(this)
                    .statusBarColor(color)
                    .navigationBarColor(R.color.color_dn_black_white)
                    .init()
    }
}